package com.shinemo.mpush.alloc.service;

import com.mpush.tools.Jsons;
import com.shinemo.mpush.alloc.cache.redis.manager.JedisUtil;
import com.shinemo.mpush.alloc.domain.NotificationDO;
import com.shinemo.mpush.alloc.domain.OfflineMsgVo;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * Created by ThinkPad on 2017/9/23.
 */
public class OfflineMsgServiceImp implements IOfflineMsgService{

    public void saveOfflineMsg(String userId,NotificationDO notificationDO) {
        Jedis jedis=JedisUtil.getInstance().getJedis();
        String json = Jsons.toJson(notificationDO);
        try {
            //TODO 没有设置消息的过期时间
            jedis.hset("mp:msg:" + notificationDO.getMsgId(), notificationDO.getMsgId(), json);
        }catch (Exception e){
        }
        JedisUtil.getInstance().returnJedis(jedis);
    }

    @Override
    public boolean saveOfflineMsg(String userId, OfflineMsgVo offlineMsg) {
        Jedis jedis=JedisUtil.getInstance().getJedis();
        String json = Jsons.toJson(offlineMsg);
        try {
            jedis.hset("mp:msg:" + userId, offlineMsg.getMsgId(), json);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            JedisUtil.getInstance().returnJedis(jedis);
        }
    }

    @Override
    public boolean saveOfflineMsg(List<String> userIds, OfflineMsgVo offlineMsg) {
        for (String userId:userIds){
            saveOfflineMsg(userId,offlineMsg);
        }
        return true;
    }

    @Override
    public void delOfflineMsg(String userId, String msgId) {
        Jedis jedis=JedisUtil.getInstance().getJedis();
        try {
            jedis.hdel("mp:msg:"+userId,msgId);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JedisUtil.getInstance().returnJedis(jedis);
        }
    }
}
